package com.wtgroup.demo.牛客;

/**
 * @author nisus
 * @version 0.1
 * @since 2023/6/6 12:02
 */
public class HJ107_求解立方根 {
    public static void main(String[] args) {
        double r = D.func(11);
        System.out.println(r);
        double r2 = S.func(11);
        System.out.println(r2);
    }

    // 推荐
    static class S {

        static double func(double target) {
            // 根据题意, -27~27 足够, |target| < 20, 即, -3^3~3^3
            double low = -3, hight = 3;
            double epison = 0.0001;
            double ans;
            while (true) {
                ans = low + (hight - low) / 2;
                double mul = ans * ans * ans;
                double error = mul - target;
                if (error > epison) {
                    hight = ans;
                    continue;
                }
                if (error < -epison) {
                    low = ans;
                    continue;
                }
                break;
            }

            return ans;
        }

    }


    // 啰嗦了
    // !!! 涉及到浮点数, 一定要有个精度, 否则几容易陷入死循环
    static class D {
        static double func(double target) {
            double targetAbs = Math.abs(target);
            double low = 0;
            double hight = 3; // 27
            double ans = 0;
            double p = 0.0001;
            while (low <= hight) {
                double mid = (hight - low) / 2 + low;
                double mid3 = mid * mid * mid;
                boolean flag = mid == low;
                double diff = Math.abs(mid3 - targetAbs);
                if (diff <= p) {
                    ans = mid;
                    break;
                }
                if (mid3 < targetAbs) {
                    low = mid;
                    ans = mid;
                } else {
                    hight = mid;
                }

                if (flag) {
                    break;
                }
            }

            return target < 0 ? -ans : ans;
        }
    }

}
